package tictactoe.GUI;


import tictactoe.Player;
import tictactoe.exceptions.network.NetworkException;
import tictactoe.multiplayer.client.Client;
import java.awt.Point;
import java.util.Set;
import javax.naming.event.EventDirContext;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

public class ClientImpl extends Client {
    private NewMultiplayer multiplayerWin;
    private GameWindow gameWin;

    public ClientImpl(String server, NewMultiplayer dialog) throws NetworkException {
        super(server);
        multiplayerWin = dialog;
    }

    public void setGameWindow(GameWindow dialog) {
        gameWin = dialog;
        multiplayerWin = null;
    }

    public JDialog getActiveWin() {
        if (multiplayerWin != null) {
            return multiplayerWin;
        }
        if (gameWin != null) {
            return gameWin;
        }

        throw new IllegalStateException("no dialogs set!");
    }

    @Override
    public void connectionAcknowledged() {
        //ok
    }

    @Override
    public void exceptionReceived(String message) {
        JOptionPane.showMessageDialog(getActiveWin(), message);
    }

    @Override
    public void moveReceived(Point move) {
        if (gameWin != null) {
            gameWin.remoteTurn(move);
        }
    }

    @Override
    public void oponentDisconnected() {
        JOptionPane.showMessageDialog(getActiveWin(), "Oponent disconnected, you won");
    }

    @Override
    public void playRequestReceived(Player from) {
        if (multiplayerWin != null) {
            int choice = JOptionPane.showConfirmDialog(multiplayerWin,
                            "Player " + from.getName() + " has challenged you to play",
                            "Challenge request",
                            JOptionPane.YES_NO_OPTION);

                    if (choice == JOptionPane.YES_OPTION) {
                        acceptChallenge(from);
                        multiplayerWin.startGame(from, getPlayer());
                    }
        }
    }

    @Override
    public void playersSetReceived(Set<Player> players) {
        if (multiplayerWin != null) {
            multiplayerWin.playersSetReceived(players);
        }
    }

    @Override
    public void receivedMessage(String msg) {
        System.out.println(msg);
        //ok
    }

    @Override
    public void requestAccepted(Player from) {
        if (multiplayerWin != null) {
            multiplayerWin.startGame(getPlayer(), from);
        }
    }

    @Override
    public void serverShuttingDown() {
        JOptionPane.showMessageDialog(getActiveWin(), "Server shutting down, thank you for playing");
    }


}
